<?php
/**
* product.php
*
* Create on 2017-2-17
* Create by TT
*/
namespace haibao\cms\data\newproduct;

class Product extends \haibao\cms\data\BaseMysql{

	private static $cacheProductPropertyList = 'ProductPropertyList';
	
	public function __construct(){
		parent::__construct('\haibao\cms\model\data\newproduct\Product');
	}
	
	public function addProductPropertyRelationModels($productId,$models){
		self::beginTranscation();
		try{
			$sql = 'delete from ProductPropertyRelation where ProductId=%s';
			$this->query($sql,array($productId));
			$this->addAll($models);
		}catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	/**
	 * 
	 * @param \haibao\cms\model\data\newproduct\Product $model
	 * @param array $brandIds
	 */
	public function addProduct($model,$brandIdArr,$categoryIdArr){
		self::beginTranscation();
		try{
			$this->add($model);
			
			$this->addProductBrandGroup($model->Id,$brandIdArr);
			
			$this->addProductCategoryRelation($model->Id,$categoryIdArr);

            $productPropertyModels = array();
		    //默认所有产品都添加价格属性
            $propertyModel = new \haibao\cms\model\data\newproduct\ProductPropertyRelation();
            $propertyModel->ProductId = $model->Id;
            $propertyModel->PropertyId = 1;
            $propertyModel->PropertyName = '价格';
            $propertyModel->DataType = 3;
            $propertyModel->DefaultValue = 'USD,RMB,EUR,GBP,HKD';
            $productPropertyModels[] = $propertyModel;

		    //如果是美妆类的，需要添加“量”属性
            $beautyCategoryIds = array(138,133,128,107,97,96,95,41);
            $categoryData = new \haibao\cms\data\newproduct\ProductCategory();
            foreach ($categoryIdArr as $categoryId){
                $categoryVal = $categoryData->getCategoryById($categoryId);
                foreach ($categoryVal->ParentIds as $parentInfo){
                    if(in_array($parentInfo->ParentId,$beautyCategoryIds)){
                        $propertyModel = new \haibao\cms\model\data\newproduct\ProductPropertyRelation();
                        $propertyModel->ProductId = $model->Id;
                        $propertyModel->PropertyId = 3;
                        $propertyModel->PropertyName = '量';
                        $propertyModel->DataType = 3;
                        $propertyModel->DefaultValue = 'g,ml';
                        $productPropertyModels[] = $propertyModel;
                        break;
                    }
                }
            }
            $this->addAll($productPropertyModels);

		}catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	public function copyProduct($productId,$userId){
		$newProductId = 0;
		self::beginTranscation();
		try{
			$model = new \haibao\cms\model\data\newproduct\Product();
			$model->ProductName = '';
			$model->Season = '';
			$model->SeasonYear = 0;
			$model->ProductSeries = '';
			$model->CreateBy = $userId;
			$model->Status = \haibao\cms\model\data\newproduct\Product::STATUS_ENABLE;
			$model->CreateTime = new \DateTime();
			$this->add($model);
			
			$productPropertyModels = array();
			$sql ="select PropertyId,PropertyName,DataType,DefaultValue from ProductPropertyRelation where ProductId=%s";
			$result = $this->query($sql,array($productId));
			while($result->fetch_assoc()){
				$propertyModel = new \haibao\cms\model\data\newproduct\ProductPropertyRelation();
				$propertyModel->ProductId = $model->Id;
				$propertyModel->PropertyId = $result->getData('PropertyId');
				$propertyModel->PropertyName = $result->getData('PropertyName');
				$propertyModel->DataType = $result->getData('DataType');
				$propertyModel->DefaultValue = $result->getData('DefaultValue');
				$productPropertyModels[] = $propertyModel;
			}
			
			if($productPropertyModels){
				$this->addAll($productPropertyModels);
			}
			
			
			$brandIdArr = array();
			$sql ="select BrandId from ProductBrandGroup_New where ProductId=%s";
			$result = $this->query($sql,array($productId));
			while($result->fetch_assoc()){
				$brandIdArr[] = $result->getData('BrandId');
			}
			$this->addProductBrandGroup($model->Id,$brandIdArr);
			
			$categoryIdArr = array();
			$sql ="select CategoryId from ProductCategoryRelation where ProductId=%s";
			$result = $this->query($sql,array($productId));
			while($result->fetch_assoc()){
				$categoryIdArr[] = $result->getData('CategoryId');
			}
				
			$this->addProductCategoryRelation($model->Id,$categoryIdArr);
			
			$newProductId = $model->Id;
		}catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
		
		return $newProductId;
	}
	
	public function updateProduct($id, $arrSet,$brandIds,$categoryIdArr){
		self::beginTranscation();
		try{
			parent::updateById($id, $arrSet);
				
			$sql = 'delete from ProductBrandGroup_New where ProductId=%s';
			$this->query($sql,array($id));
	
			$this->addProductBrandGroup($id,$brandIds);
			
			$sql = 'delete from ProductCategoryRelation where ProductId=%s';
			$this->query($sql,array($id));
			
			$this->addProductCategoryRelation($id,$categoryIdArr);
			
		}catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	public function updateProductStatus($id,$status = \haibao\cms\model\data\newproduct\Product::STATUS_ENABLE){
		self::beginTranscation();
		try{
			$sql = 'update Product_New set Status=%s where Id=%s';
			$arrValues = array($status,$id);
			$this->query($sql,$arrValues);
				
			$goodsData = new \haibao\cms\data\newproduct\Goods();
			$goodsData->updateStatusByProductId($id,$status);
		}catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	public function addProductProperty($model){
		$this->add($model);
		$this->unsetCache(self::$cacheProductPropertyList);
	}
	
	public function getProductPropertyList(){
		$productPropertyList = $this->getCache(self::$cacheProductPropertyList);
		return $productPropertyList ? $productPropertyList : $this->setProductPropertyList();
	}
	
	private function setProductPropertyList(){
		$productPropertyList = array();
		
		$sql ="select * from ProductProperty";
		$result = $this->query($sql);
		
		while($result->fetch_assoc()){
			$productPropertyList[$result->getData('Id')] = array('Name'=>$result->getData('Name'),'DataType'=>$result->getData('DataType'));
		}
		
		if($productPropertyList){
			$this->setCache(self::$cacheProductPropertyList, $productPropertyList);
		}
		
		return $productPropertyList;
	}
	
	private function addProductBrandGroup($productId,$brandIdArr){
		if(!empty($brandIdArr)){
			$arrValues = array();
			$arrSql = array();
			foreach($brandIdArr as $id){
				array_push($arrSql,'(%s,%s)');
				array_push($arrValues,$id);
				array_push($arrValues,$productId);
			}
	
			$sql = "insert into ProductBrandGroup_New (BrandId,ProductId) values";
			$sql .= implode(',', $arrSql);
			$this->query($sql,$arrValues);
		}
	}
	
	private function addProductCategoryRelation($productId,$categoryIdArr){
		if(!empty($categoryIdArr)){
			$arrValues = array();
			$arrSql = array();
			foreach($categoryIdArr as $id){
				array_push($arrSql,'(%s,%s)');
				array_push($arrValues,$id);
				array_push($arrValues,$productId);
			}
	
			$sql = "insert into ProductCategoryRelation (CategoryId,ProductId) values";
			$sql .= implode(',', $arrSql);
			$this->query($sql,$arrValues);
		}
	}
}